<?php
header('Content-Type: text/html; charset=utf-8');

// 定义站点地图URL和百度站长平台API地址
$SITEMAP_URL = "http://你的域名/sitemap.xml";
$BAIDU_API_URL = '百度站长的推送接口';

try {
    // 获取站点地图内容
    $xmldata = @file_get_contents($SITEMAP_URL);
    if ($xmldata === FALSE) {
        throw new Exception('无法获取站点地图内容');
    }

    // 解析XML数据
    $xml = simplexml_load_string($xmldata, 'SimpleXMLElement', LIBXML_NOCDATA);
    if ($xml === FALSE) {
        throw new Exception('解析XML数据失败');
    }

    // 提取所有URL
    $urls = [];
    foreach ($xml->url as $urlElement) {
        $loc = (string)$urlElement->loc;
        echo htmlspecialchars($loc) . "<br/>";
        $urls[] = $loc;
    }

    if (empty($urls)) {
        throw new Exception('没有找到任何URL');
    }

    // 初始化CURL
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $BAIDU_API_URL,
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => implode("\n", $urls),
        CURLOPT_HTTPHEADER => ['Content-Type: text/plain'],
    ]);

    // 执行CURL请求并检查结果
    $result = curl_exec($ch);
    if ($result === FALSE) {
        throw new Exception('CURL请求失败: ' . curl_error($ch));
    }

    echo '推送结果: ' . htmlspecialchars($result);

} catch (Exception $e) {
    echo '错误: ' . htmlspecialchars($e->getMessage());
}

// 关闭CURL资源
if (isset($ch)) {
    curl_close($ch);
}
?>